using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(Material))]
[CanEditMultipleObjects]
public class FX_Uber_SmokeShaderGUI : ShaderGUI
{
    // 选择列表
    private static readonly string[] smokeRenderModeOptions = new string[] {
        "Unit", "Diffuse", "Normal", "Sixway"
    };

    private static readonly string[] flipbookModeOptions = new string[] {
        "Simple", "Blend", "MotionVector"
    };

    // 材质属性
    private MaterialProperty smokeRenderMode;
    private MaterialProperty colorAdjust;
    private MaterialProperty lightInt;
    private MaterialProperty colorContrast;
    private MaterialProperty colorFlip;
    private MaterialProperty softParticle;
    private MaterialProperty alphaSoft;
    private MaterialProperty addMode;
    private MaterialProperty mulMode;
    private MaterialProperty flipbookMode;
    private MaterialProperty flipSize;
    private MaterialProperty motionVectors;
    private MaterialProperty motionVectorIntensity;
    private MaterialProperty smokeRTBA_P;
    private MaterialProperty smokeLBF_N;
    private MaterialProperty smokeTex;
    private MaterialProperty smokeNormal;
    private MaterialProperty normalStrength;
    private MaterialProperty shadowInt;
    private MaterialProperty softShadow;
    private MaterialProperty useRamp;
    private MaterialProperty attenuationRamp;
    private MaterialProperty queueOffset;
    private MaterialProperty queueControl;
    private MaterialProperty unity_Lightmaps;
    private MaterialProperty unity_LightmapsInd;
    private MaterialProperty unity_ShadowMasks;

    // 折叠状态
    private bool baseSettingsFoldout = true;
    private bool flipbookSettingsFoldout = true;
    private bool textureSettingsFoldout = true;
    private bool advancedSettingsFoldout = false;

    // 样式设置
    private GUIStyle boldFoldoutStyle;
    private GUIStyle miniBoldLabelStyle;
    private GUIStyle sectionBoxStyle;
    private GUIStyle advancedFoldoutStyle;
    private GUIStyle textureGroupStyle;
    private GUIStyle advancedContentStyle;
    private GUIStyle categoryHeaderStyle;
    private GUIStyle advancedHeaderStyle;
    private GUIStyle titleBoxStyle;
    private GUIStyle smallLabelStyle;
    private GUIStyle brightButtonStyle;

    // 渐变纹理
    private Texture2D categoryHeaderGradient;
    private Texture2D advancedHeaderGradient;

    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
    {
        // 初始化样式
        InitializeStyles();

        // 查找材质属性
        FindProperties(properties);

        // 获取当前编辑的所有材质
        Material[] materials = new Material[materialEditor.targets.Length];
        for (int i = 0; i < materialEditor.targets.Length; i++)
        {
            materials[i] = materialEditor.targets[i] as Material;
        }

        // 开始 GUI 更改检查
        EditorGUI.BeginChangeCheck();

        // 绘制标题和折叠按钮
        DrawTitleAndFoldButtons();

        // 绘制基础设置折叠项
        DrawFoldoutWithGradientBackground(ref baseSettingsFoldout, "基础设置", boldFoldoutStyle, categoryHeaderGradient);
        if (baseSettingsFoldout)
        {
            using (new EditorGUILayout.VerticalScope(sectionBoxStyle))
            {
                DrawEnumPopup(materialEditor, smokeRenderMode, "烟雾渲染模式", smokeRenderModeOptions);
                DrawShaderProperty(materialEditor, colorAdjust, "颜色调整");
                DrawShaderProperty(materialEditor, lightInt, "光照强度");
                DrawShaderProperty(materialEditor, colorContrast, "颜色对比度");
                DrawShaderProperty(materialEditor, colorFlip, "颜色反转");
                DrawShaderProperty(materialEditor, softParticle, "软粒子");
                DrawShaderProperty(materialEditor, alphaSoft, "透明区域羽化");
                DrawShaderProperty(materialEditor, addMode, "加法模式");
                DrawShaderProperty(materialEditor, mulMode, "乘法模式");
            }
        }
        EditorGUILayout.Space();

        // 绘制翻页书设置折叠项
        DrawFoldoutWithGradientBackground(ref flipbookSettingsFoldout, "翻页书模式设置", boldFoldoutStyle, categoryHeaderGradient);
        if (flipbookSettingsFoldout)
        {
            using (new EditorGUILayout.VerticalScope(sectionBoxStyle))
            {
                DrawEnumPopup(materialEditor, flipbookMode, "翻页书模式", flipbookModeOptions);
                DrawShaderProperty(materialEditor, flipSize, "翻页书尺寸");
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("运动向量纹理"), motionVectors);
                DrawShaderProperty(materialEditor, motionVectorIntensity, "运动向量强度");
            }
        }
        EditorGUILayout.Space();

        // 绘制纹理设置折叠项
        DrawFoldoutWithGradientBackground(ref textureSettingsFoldout, "纹理设置", boldFoldoutStyle, categoryHeaderGradient);
        if (textureSettingsFoldout)
        {
            using (new EditorGUILayout.VerticalScope(sectionBoxStyle))
            {
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("烟雾 RTBA_P 纹理"), smokeRTBA_P);
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("烟雾 LBF_N 纹理"), smokeLBF_N);
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("烟雾纹理"), smokeTex);
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("烟雾法线纹理"), smokeNormal);
                DrawShaderProperty(materialEditor, normalStrength, "法线强度");
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("unity_Lightmaps"), unity_Lightmaps);
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("unity_LightmapsInd"), unity_LightmapsInd);
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("unity_ShadowMasks"), unity_ShadowMasks);
            }
        }
        EditorGUILayout.Space();

        // 绘制高级设置折叠项
        DrawFoldoutWithGradientBackground(ref advancedSettingsFoldout, "高级设置", advancedFoldoutStyle, advancedHeaderGradient);
        if (advancedSettingsFoldout)
        {
            using (new EditorGUILayout.VerticalScope(sectionBoxStyle))
            {
                DrawShaderProperty(materialEditor, shadowInt, "阴影强度");
                DrawShaderProperty(materialEditor, softShadow, "软阴影");
                DrawShaderProperty(materialEditor, useRamp, "使用渐变纹理");
                DrawTexturePropertySingleLine(materialEditor, new GUIContent("衰减渐变纹理"), attenuationRamp);
                DrawShaderProperty(materialEditor, queueOffset, "队列偏移");
                DrawShaderProperty(materialEditor, queueControl, "队列控制");
            }
        }

        // 应用更改
        if (EditorGUI.EndChangeCheck())
        {
            // 更新所有材质的关键字
            foreach (Material material in materials)
            {
                UpdateMaterialKeywords(material);
            }

            materialEditor.PropertiesChanged();
        }
    }

    // 绘制标题和折叠按钮
    private void DrawTitleAndFoldButtons()
    {
        using (new EditorGUILayout.HorizontalScope(titleBoxStyle))
        {
            EditorGUILayout.LabelField("新着色器界面", EditorStyles.boldLabel);

            GUILayout.FlexibleSpace();

            GUI.color = AreAllBaseFoldoutsOpen() ? Color.white : new Color(0.7f, 0.7f, 0.7f);
            if (GUILayout.Button("基础设置展开", brightButtonStyle))
            {
                bool allOpen = baseSettingsFoldout && flipbookSettingsFoldout && textureSettingsFoldout;
                baseSettingsFoldout = !allOpen;
                flipbookSettingsFoldout = !allOpen;
                textureSettingsFoldout = !allOpen;
            }

            GUI.color = AreAllAdvancedFoldoutsOpen() ? Color.white : new Color(0.7f, 0.7f, 0.7f);
            if (GUILayout.Button("专业设置展开", brightButtonStyle))
            {
                advancedSettingsFoldout = !advancedSettingsFoldout;
            }
            GUI.color = Color.white;
        }
    }

    // 检查所有基础折叠项是否展开
    private bool AreAllBaseFoldoutsOpen()
    {
        return baseSettingsFoldout && flipbookSettingsFoldout && textureSettingsFoldout;
    }

    // 检查所有高级折叠项是否展开
    private bool AreAllAdvancedFoldoutsOpen()
    {
        return advancedSettingsFoldout;
    }

    // 绘制带渐变背景的折叠项
    private void DrawFoldoutWithGradientBackground(ref bool foldout, string title, GUIStyle style, Texture2D gradientTexture)
    {
        Rect rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight);

        // 绘制渐变背景
        if (gradientTexture != null)
        {
            EditorGUI.DrawPreviewTexture(rect, gradientTexture);
        }

        // 绘制折叠按钮
        foldout = EditorGUI.Foldout(rect, foldout, title, true, style);
    }

    // 绘制枚举下拉框
    private void DrawEnumPopup(MaterialEditor materialEditor, MaterialProperty property, string label, string[] options)
    {
        if (property == null)
        {
            EditorGUILayout.HelpBox($"属性 '{label}' 不存在于当前 shader 中", MessageType.Warning);
            return;
        }

        EditorGUI.showMixedValue = property.hasMixedValue;
        EditorGUI.BeginChangeCheck();

        int index = (int)property.floatValue;
        index = EditorGUILayout.Popup(label, index, options);

        if (EditorGUI.EndChangeCheck())
        {
            property.floatValue = index;
        }
        EditorGUI.showMixedValue = false;
    }

    // 绘制材质属性
    private void DrawShaderProperty(MaterialEditor materialEditor, MaterialProperty property, string label)
    {
        EditorGUI.showMixedValue = property.hasMixedValue;
        materialEditor.ShaderProperty(property, label);
        EditorGUI.showMixedValue = false;
    }

    // 绘制纹理属性
    private void DrawTexturePropertySingleLine(MaterialEditor materialEditor, GUIContent label, MaterialProperty property)
    {
        EditorGUI.showMixedValue = property.hasMixedValue;
        materialEditor.TexturePropertySingleLine(label, property);
        EditorGUI.showMixedValue = false;
    }

    // 初始化自定义样式
    private void InitializeStyles()
    {
        if (boldFoldoutStyle == null)
        {
            boldFoldoutStyle = new GUIStyle(EditorStyles.foldout);
            boldFoldoutStyle.fontStyle = FontStyle.Bold;
            boldFoldoutStyle.fontSize = 12;
            boldFoldoutStyle.margin = new RectOffset(10, 0, 0, 0);
        }

        if (advancedFoldoutStyle == null)
        {
            advancedFoldoutStyle = new GUIStyle(EditorStyles.foldout);
            advancedFoldoutStyle.fontStyle = FontStyle.Normal;
            advancedFoldoutStyle.fontSize = 11;
            advancedFoldoutStyle.margin = new RectOffset(20, 0, 0, 0);
        }

        if (miniBoldLabelStyle == null)
        {
            miniBoldLabelStyle = new GUIStyle(EditorStyles.miniBoldLabel);
            miniBoldLabelStyle.margin = new RectOffset(15, 0, 5, 5);
        }

        if (sectionBoxStyle == null)
        {
            sectionBoxStyle = new GUIStyle(GUI.skin.box);
            sectionBoxStyle.margin = new RectOffset(10, 10, 5, 5);
            sectionBoxStyle.padding = new RectOffset(10, 10, 10, 10);
            sectionBoxStyle.border = new RectOffset(1, 1, 1, 1);
        }

        if (textureGroupStyle == null)
        {
            textureGroupStyle = new GUIStyle(GUI.skin.box);
            textureGroupStyle.margin = new RectOffset(5, 5, 5, 5);
            textureGroupStyle.padding = new RectOffset(10, 10, 10, 10);
            textureGroupStyle.border = new RectOffset(1, 1, 1, 1);
            textureGroupStyle.normal.background = CreateColoredTexture(new Color(0.15f, 0.15f, 0.15f, 0.2f));
        }

        if (advancedContentStyle == null)
        {
            advancedContentStyle = new GUIStyle(GUI.skin.box);
            advancedContentStyle.margin = new RectOffset(15, 15, 5, 5);
            advancedContentStyle.padding = new RectOffset(10, 10, 10, 10);
            advancedContentStyle.border = new RectOffset(1, 1, 1, 1);
            advancedContentStyle.normal.background = CreateColoredTexture(new Color(0.1f, 0.1f, 0.1f, 0.2f));
        }

        if (categoryHeaderStyle == null)
        {
            categoryHeaderStyle = new GUIStyle();
            // 此处不需要设置样式因为已经有渐变背景
        }

        if (advancedHeaderStyle == null)
        {
            advancedHeaderStyle = new GUIStyle();
            // 此处不需要设置样式因为已经有渐变背景
        }

        if (titleBoxStyle == null)
        {
            titleBoxStyle = new GUIStyle(GUI.skin.box);
            titleBoxStyle.normal.background = CreateColoredTexture(Color.black);
            titleBoxStyle.padding = new RectOffset(10, 10, 5, 5);
        }

        if (smallLabelStyle == null)
        {
            smallLabelStyle = new GUIStyle(EditorStyles.label);
            smallLabelStyle.fontSize = 10;
            smallLabelStyle.alignment = TextAnchor.MiddleLeft;
        }

        if (brightButtonStyle == null)
        {
            brightButtonStyle = new GUIStyle(GUI.skin.button);
            brightButtonStyle.normal.textColor = Color.white;
        }

        // 初始化渐变纹理
        if (categoryHeaderGradient == null)
        {
            // 类别标题的渐变 - 灰色
            categoryHeaderGradient = CreateGradientTexture(256, 1, new Color(0.2f, 0.2f, 0.2f, 0.3f), new Color(0.1f, 0.1f, 0.1f, 0.4f));
        }

        if (advancedHeaderGradient == null)
        {
            // 高级设置标题的渐变 - 深灰色
            advancedHeaderGradient = CreateGradientTexture(256, 1, new Color(0.15f, 0.15f, 0.15f, 0.4f), new Color(0.05f, 0.05f, 0.05f, 0.5f));
        }
    }

    // 创建纯色纹理
    private Texture2D CreateColoredTexture(Color color)
    {
        Texture2D texture = new Texture2D(1, 1);
        texture.SetPixel(0, 0, color);
        texture.Apply();
        return texture;
    }

    // 创建渐变纹理
    private Texture2D CreateGradientTexture(int width, int height, Color startColor, Color endColor)
    {
        Texture2D texture = new Texture2D(width, height);
        for (int x = 0; x < width; x++)
        {
            float t = (float)x / (width - 1);
            Color color = Color.Lerp(startColor, endColor, t);
            for (int y = 0; y < height; y++)
            {
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();
        return texture;
    }

    // 查找材质属性
    private void FindProperties(MaterialProperty[] properties)
    {
        smokeRenderMode = FindProperty("_SMOKERENDERMODE", properties, false);
        colorAdjust = FindProperty("_ColorAdjust", properties, false);
        lightInt = FindProperty("_LightInt", properties, false);
        colorContrast = FindProperty("_ColorContrast", properties, false);
        colorFlip = FindProperty("_ColorFlip", properties, false);
        softParticle = FindProperty("_SoftParticle", properties, false);
        alphaSoft = FindProperty("_AlphaSoft", properties, false);
        addMode = FindProperty("_AddMode", properties, false);
        mulMode = FindProperty("_MulMode", properties, false);
        flipbookMode = FindProperty("_FLIPBOOKMODE", properties, false);
        flipSize = FindProperty("_FlipSize", properties, false);
        motionVectors = FindProperty("_D0C61C21", properties, false);
        motionVectorIntensity = FindProperty("_3D7870AC", properties, false);
        smokeRTBA_P = FindProperty("_SmokeRTBA_P", properties, false);
        smokeLBF_N = FindProperty("_SmokeLBF_N", properties, false);
        smokeTex = FindProperty("_SmokeTex", properties, false);
        smokeNormal = FindProperty("_SmokeNormal", properties, false);
        normalStrength = FindProperty("_NormalStrength", properties, false);
        shadowInt = FindProperty("_ShadowInt", properties, false);
        softShadow = FindProperty("_SoftShadow", properties, false);
        useRamp = FindProperty("_USERAMP", properties, false);
        attenuationRamp = FindProperty("_AttenuationRamp", properties, false);
        queueOffset = FindProperty("_QueueOffset", properties, false);
        queueControl = FindProperty("_QueueControl", properties, false);
        unity_Lightmaps = FindProperty("unity_Lightmaps", properties, false);
        unity_LightmapsInd = FindProperty("unity_LightmapsInd", properties, false);
        unity_ShadowMasks = FindProperty("unity_ShadowMasks", properties, false);
    }

    // 更新材质关键字
    private void UpdateMaterialKeywords(Material material)
    {
        // 根据 _FLIPBOOKMODE 设置关键字
        int flipbookModeIndex = (int)material.GetFloat("_FLIPBOOKMODE");
        material.DisableKeyword("_FLIPBOOKMODE_SIMPLE");
        material.DisableKeyword("_FLIPBOOKMODE_BLEND");
        material.DisableKeyword("_FLIPBOOKMODE_MOTIONVECTOR");
        switch (flipbookModeIndex)
        {
            case 0:
                material.EnableKeyword("_FLIPBOOKMODE_SIMPLE");
                break;
            case 1:
                material.EnableKeyword("_FLIPBOOKMODE_BLEND");
                break;
            case 2:
                material.EnableKeyword("_FLIPBOOKMODE_MOTIONVECTOR");
                break;
        }

        // 根据 _SMOKERENDERMODE 设置关键字
        int smokeRenderModeIndex = (int)material.GetFloat("_SMOKERENDERMODE");
        material.DisableKeyword("_SMOKERENDERMODE_UNIT");
        material.DisableKeyword("_SMOKERENDERMODE_DIFFUSE");
        material.DisableKeyword("_SMOKERENDERMODE_NORMAL");
        material.DisableKeyword("_SMOKERENDERMODE_SIXWAY");
        switch (smokeRenderModeIndex)
        {
            case 0:
                material.EnableKeyword("_SMOKERENDERMODE_UNIT");
                break;
            case 1:
                material.EnableKeyword("_SMOKERENDERMODE_DIFFUSE");
                break;
            case 2:
                material.EnableKeyword("_SMOKERENDERMODE_NORMAL");
                break;
            case 3:
                material.EnableKeyword("_SMOKERENDERMODE_SIXWAY");
                break;
        }

        // 根据 _USERAMP 设置关键字
        bool useRampValue = material.GetFloat("_USERAMP") == 1;
        if (useRampValue)
        {
            material.EnableKeyword("_USERAMP");
        }
        else
        {
            material.DisableKeyword("_USERAMP");
        }
    }
}